package se.opendataexchange.rockwell;

import java.io.IOException;

import se.opendataexchange.common.AbstractControlSystem;
import se.opendataexchange.common.ErrorInfo;
import se.opendataexchange.common.polling.PollManager;
import se.opendataexchange.controller.OpenDataExchangeController;
import se.opendataexchange.ethernetip4j.Log;

public class RockwellController extends AbstractControlSystem implements Runnable{

	private LogixCommunicator logixController ;
	private PollManager pollMgr;
	private boolean runner=false;
	private boolean connected=false;
	private Thread ndThread;
	public RockwellController() {
		// TODO Auto-generated constructor stub
	}

	public LogixCommunicator getLogixController() {
		return logixController;
	}

	public void setLogixController(LogixCommunicator logixController) {
		this.logixController = logixController;
	}

	public PollManager getPollMgr() {
		return pollMgr;
	}

	public void setPollMgr(PollManager pollMgr) {
		this.pollMgr = pollMgr;
	}

	public void init(){
		super.init();
		pollMgr.init();
		setDataSource(logixController);
	}
	
	@Override
	public void start() {
		pollMgr.start();
		ndThread = new Thread(this);
		connected=true;
		ndThread.start();
		try {
			logixController.connect();
		} catch (IOException e) {
			e.printStackTrace();
			Log.p(e.getMessage());
		}
		super.start();
	}
	
	@Override
	public void stop() {
		pollMgr.stop();
		runner = false;
		try {
			logixController.disconnect();
		} catch (IOException e) {
			e.printStackTrace();
			Log.p(e.getMessage());
		}
		super.stop();
	}
	
	@Override
	public void pause() {
		pollMgr.stop();
		super.pause();
	}

	@Override
	public void run() {
		runner = true;
		//Check if we are to be connected and is connected.
		while(runner){
			if(connected == false){
				if(logixController.isConnected()){
					try{
						logixController.disconnect();
					}catch (Exception e) {
						//e.printStackTrace();
						Log.p(e.getMessage());
						OpenDataExchangeController.reportError(new ErrorInfo(e.getMessage()));
					}
				}
			}else{
				if(!logixController.isConnected()){
					try{
						logixController.connect();
					}catch (Exception e) {
						//e.printStackTrace();
						Log.p(e.getMessage());
						OpenDataExchangeController.reportError(new ErrorInfo(e.getMessage()));
					}
				}
			}
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		Log.p("Connection thread ended.");
	}
}
